package com.cashmama.market.api.domain.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cashmama.market.api.domain.vo.contact.CallVO;
import com.cashmama.market.api.domain.vo.contact.SmsVO;
import com.cashmama.market.api.infras.enums.error.UserProfileErrorCodeEnum;
import com.cashmama.market.api.infras.exception.ApplicationException;
import com.cashmama.market.api.infras.utils.HttpUtil;
import com.fqgj.common.api.Page;
import com.fqgj.common.api.Response;
import com.fqgj.xjd.user.client.UserContactService;
import com.fqgj.xjd.user.client.UserService;
import com.fqgj.xjd.user.client.response.UserContactAddressBook;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @program: market-api
 * @description
 * @author: frank
 * @create: 2019-12-25 11:35
 **/
@Service
public class SyncContactService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SyncContactService.class);
    @Autowired
    private UserContactService userContactService;
    @Autowired
    private UserService userService;

    /**
     * 分页获取短信记录
     */
    public List<SmsVO> getUserSmsByPage(String userCode, Page page) {

        try {
            String data = getUserContactData(userCode);
            JSONObject jsonObject = JSONObject.parseObject(data);
            JSONArray smsList = jsonObject.getJSONArray("smsList");
            page.setTotalCount(smsList.size());
            List<SmsVO> smsVOS = new ArrayList<>();
            //分页
            smsList.stream().skip((page.getCurrentPage() - 1) * page.getPageSize()).limit(page.getPageSize()).forEach(e -> {
                SmsVO smsVO = JSONObject.toJavaObject((JSONObject) e, SmsVO.class);
                smsVOS.add(smsVO);
            });
            return smsVOS;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 分页获取通话记录
     */
    public List<CallVO> getCallsByPage(String userCode, Page page) {
        try {
            String data = getUserContactData(userCode);
            JSONObject jsonObject = JSONObject.parseObject(data);
            JSONArray callList = jsonObject.getJSONArray("calls");
            page.setTotalCount(callList.size());
            List<CallVO> callVOS = new ArrayList<>();
            //分页
            callList.stream().skip((page.getCurrentPage() - 1) * page.getPageSize()).limit(page.getPageSize()).forEach(e -> {
                CallVO callVO = JSONObject.toJavaObject((JSONObject) e, CallVO.class);
                callVOS.add(callVO);
            });
            return callVOS;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 通话记录和短信 是否存在
     */
    void checkContactInfo(String userCode) {
        try {
            String data = getUserContactData(userCode);
            JSONObject jsonObject = JSONObject.parseObject(data);
            JSONArray callList = jsonObject.getJSONArray("calls");
            JSONArray smsList = jsonObject.getJSONArray("smsList");
            boolean incomplete = callList == null || smsList == null || callList.size() < 1 || smsList.size() < 1;
            if (incomplete) {
                LOGGER.info("====通话记录不完整===userCode:{}", userCode);
                throw new ApplicationException(UserProfileErrorCodeEnum.USER_CONTACT_INFO_NOT_COMPLETE);
            }
        } catch (Exception e) {
            throw new ApplicationException(UserProfileErrorCodeEnum.USER_CONTACT_INFO_NOT_COMPLETE);
        }
    }

    /**
     * 获取oss数据
     */
    private String getUserContactData(String userCode) throws Exception {
        Response<UserContactAddressBook> userContactAddressBookResponse = userContactService.getUserDeviceContactByUserCode(userCode);
        String url = Optional.ofNullable(userContactAddressBookResponse).filter(Response::isSuccess)
                .map(Response::getData).map(UserContactAddressBook::getContactUrl).orElse("");
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url不存在");
        }
        //换成内网oss,不然请求会有一定资费产生
        url = url.replace("cashmama-oss-pro.cashmama.in", "cashmama-pro.oss-ap-south-1-internal.aliyuncs.com");
        LOGGER.info("==获取通话记录和短信信息==userCode:{},url:{}", userCode, url);
        String data = HttpUtil.getPage(url);
        if (StringUtils.isEmpty(data)) {
            throw new Exception("数据为空");
        }
        return data;
    }
}
